﻿using BenchmarkDotNet.Attributes;
using Devonline.Core;

namespace Benchmark;

[SimpleJob]
[MemoryDiagnoser]
public class Fibonacci
{
    private readonly int _rank = 30;

    [Benchmark]
    public void Run()
    {
        Execute(_rank);
    }

    /// <summary>
    /// 循环执行
    /// </summary>
    /// <param name="count">循环次数</param>
    public void LoopRun(int count)
    {
        Console.WriteLine($"the benchmark of {nameof(Fibonacci)} will loop run {nameof(Run)} {count} times!");
        var startTime = DateTime.Now;
        for (int i = 0; i < count; i++)
        {
            Run();
        }

        Console.WriteLine($"the benchmark of {nameof(Fibonacci)} loop run {nameof(Run)}: " + startTime.GetTimeDetail());
    }
    /// <summary>
    /// 并发执行
    /// </summary>
    /// <param name="count">并发次数</param>
    public void ParallelRun(int count)
    {
        Console.WriteLine($"the benchmark of {nameof(Fibonacci)} will parallel run {nameof(Run)} {count} times!");
        var startTime = DateTime.Now;
        Parallel.For(0, count, (x, y) => Run());
        Console.WriteLine($"the benchmark of {nameof(Fibonacci)} parallel run {nameof(Run)}: " + startTime.GetTimeDetail());
    }

    /// <summary>
    /// 执行 Fibonacci 数列运算
    /// </summary>
    /// <param name="n"></param>
    /// <returns></returns>
    private int Execute(int n)
    {
        if (n <= 1)
        {
            return 1;
        }

        return Execute(n - 1) + Execute(n - 2);
    }
}